package org.smart4j.framework.helper;

import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.utils.ArrayUtil;
import org.smart4j.framework.utils.CollectionUtil;
import org.smart4j.framework.utils.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入帮助类
 * @Description:
 * @Author: Administrator
 * @Date: 2017/8/15 0015 下午 8:57
 */
public class IocHepler {

    static {
        /* 获取所有的Bean类与Bean实例之间对应映射关系map*/
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (CollectionUtil.isNotEmpty(beanMap)) {
            for (Map.Entry<Class<?>, Object> entry : beanMap.entrySet()) {
                /*从beanMap中获取bean类与对应的实例*/
                Class<?> beanClass = entry.getKey();
                Object beanInstance = entry.getValue();
                Field[] beanFields = beanClass.getDeclaredFields();
                /*遍历该beand类中所有的属性对象*/
                if (ArrayUtil.isNotEmpty(beanFields)) {
                    for (Field beanField : beanFields) {
                        /*如果该属性拥有Inject注解，则进行实例化*/
                        if (beanField.isAnnotationPresent(Inject.class)) {
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass);
                            if (beanFieldInstance != null) {
                                /*通过反射工具类设置bean类拥有依赖注入属性beanField的值*/
                                ReflectionUtil.setFiled(beanInstance,beanField, beanFieldInstance);
                            }
                        }
                    }
                }
            }
        }

    }

}
